package ar.edu.itba.it.paw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import ar.edu.itba.it.paw.dao.OpinionDAO;
import ar.edu.itba.it.paw.domain.ConnectionManager;
import ar.edu.itba.it.paw.domain.Opinion;
import ar.edu.itba.it.paw.domain.OpinionType;
import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.domain.exceptions.DatabaseException;

public class DatabaseOpinionDAO implements OpinionDAO {

	private static OpinionDAO instance;
	
	public static synchronized OpinionDAO getInstance(){
		if(instance == null)
			instance = new DatabaseOpinionDAO();
		return instance;
	}
	
	@Override
	public void addOpinion(Opinion opinion) {
		ConnectionManager manager = ConnectionManager.getInstance();
		Connection conn = manager.getConnection();
		PreparedStatement stmt;

		try{
			stmt = conn.prepareStatement("insert into \"Opiniones\"(contacto, tipo, comentario, user_id, fecha) values(?,?,?,?,CURRENT_DATE)");
			stmt.setString(1, opinion.getPage_firstTime());
			String str = opinion.getOpinion().toString();
			stmt.setString(2, str);
			stmt.setString(3, opinion.getComment());
			stmt.setInt(4, opinion.getUser().getId());
			stmt.execute();
			
		}catch (SQLException e){
			throw new DatabaseException();
			
		}
		
		manager.closeConnection(); 
	}

	@Override
	public List<Opinion> getAllOpinions() {

		ConnectionManager manager = ConnectionManager.getInstance();
		Connection conn = manager.getConnection();
		PreparedStatement stmt;
		
		List<Opinion> list = new ArrayList<Opinion>();
		
		try {
			stmt = conn.prepareStatement("select * from \"Opiniones\", \"Usuario\" where \"userId\" = \"user_id\" order by \"fecha\"");
			ResultSet cur = stmt.executeQuery();
			while(cur.next()){
				User user = new User(cur.getString("userName"),cur.getString("password"),cur.getString(10),cur.getString("apellido"),cur.getString("mail"));
				user.setId(cur.getInt("userId"));
				Opinion opinion = new Opinion(cur.getString("contacto"),cur.getDate("fecha"),OpinionType.valueOf(cur.getString("tipo")),cur.getString("comentario"), user);
				opinion.setId(cur.getInt("opinion_id"));
				list.add(opinion);
			}
		} catch (SQLException e) {
			throw new DatabaseException();
		}
		manager.closeConnection();
		return list;
	}

}
